package org.bee.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.bee.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonUtils {
    static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    private final static ObjectMapper mapper;
    static {
        mapper = new ObjectMapper();
    }
    /**
     * 将对象转为json字符串
     * @param obj 对象
     * @return json字符串
     */
    public static String toJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error("对象转json失败：{}", ExceptionUtils.getFullStackTrace(e));
            return null;
        }
    }

    /**
     * 将json字符串转为对象
     * @param json json字符串
     * @param clazz 对象类型
     * @return 对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (Exception e) {
            logger.error("json转对象失败：{}", ExceptionUtils.getFullStackTrace(e));
            return null;
        }
    }
}
